<?php

namespace app\api\controller;

use app\api\service\wanlshop\Common;
use app\common\controller\Api;
use fast\Http;
use app\api\model\WpsGoods;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;
use app\api\model\WpsNotice;
use app\api\model\WpsSloveNotice;
use app\api\service\wanlshop\Goods;

/**
 * 第三方平台对接
 */
class Thirdplatform extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $wpsGoodsModel = null;
    protected $wpsNoticeModel = null;
    protected $wpsSloveNoticeModel = null;
    // 商品服务
    protected $goodsService = null;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->wpsGoodsModel = new WpsGoods();
        $this->wpsNoticeModel = new WpsNotice();
        $this->wpsSloveNoticeModel = new WpsSloveNotice();
        $this->goodsService = new Goods();
    }

    public function asynchronousNotificationReception()
    {
        // 消息类型
        $params = $this->request->post();
        if (empty($params)) $this->error("参数不能为空", null, 0);
        // 根据不同类型，进行不同的逻辑
        switch ($params['type']) {
            case 2: // 价格变更
                return $this->priceChange($params);
                break;
            case 4: // 上下架变更
                $sta = $this->changeLoadingUnloading($params);
                if (!$sta[0]) {
                    $this->errorRewrite($sta[1]);
                }
                return "success";
                break;
            case 6: // 商品池
                return $this->brandLabel($params);
                break;
            case 16: // 详情数据变更
                return $this->detailsDataChange($params);
                break;
            case 28: // 售后服务单进度消息
                return $this->progressInformationServiceOrder($params);
                break;
            case 23: // 订单配送消息
                return $this->orderDeliveryMessage($params);
                break;
            case 29: // 售后地址推送
                return $this->afterSaleAddressPush($params);
                break;
            case 30: // 已选商品推送
                return $this->selectedProductPush($params);
                break;
            case 36: //充值订单消息推送
                return $this->rechargeOrderMessagePush($params);
                break;
        }
    }


    /**
     *  获取商品列表
     */

    public function getGoodsLists()
    {
        // 过滤条件
        $this->request->filter(['strip_tags']);

        // 请求参数
        $params = [
            'pageNo' => $this->request->post("pageNo", 1),
            'pageSize' => 50
        ];
        $list = Common::getData('getGoodsList', $params);
        $res = $this->goodsService->insGoods($list['list']);
        if ($res) {
            $this->success("成功", $res, 1);
        }
        $this->error("失败", null, 0);
    }

    /**
     *  获取选取商品的列表
     */
    public function getSelectGoodsLists()
    {
        // 过滤条件
        $this->request->filter(['strip_tags']);
        // 请求参数
        $params = [
            'pageNo' => $this->request->get("pageNo", 1),
            'pageSize' => 50
        ];

        $list = Common::getData('getGoodsdept', $params);
        $res = $this->goodsService->insGoods($list['list']);
        if ($res) {
            $this->success("成功", $res, 1);
        }
        $this->error("失败", null, 0);
    }


    /**
     * 商品上下架
     */
    protected function changeLoadingUnloading($params_arr)
    {

        // 开启事务
        Db::startTrans();
        try {

            // 添加异步通知
            $notice_master = [
                'c_msgid' => $params_arr['c_msgid'],
                'type' => $params_arr['type'],
                'time' => $params_arr['time']
            ];

            if (!$m_id = $this->wpsNoticeModel->insert($notice_master, false, true)) {
                throw new Exception("notice_master 添加失败");
            }

            foreach ($params_arr['c_content'] as $k => $v) {
                $slove[] = [
                    'm_id' => $m_id,
                    'c_father_goods_id' => $v['c_father_goods_id'],
                    'msg' => $v['msg'],
                    'type' => $v['type'],
                    'state' => $v['state']
                ];
            }

            if (!$this->wpsSloveNoticeModel->insertAll($slove)) {
                throw new Exception('notice_slove 添加失败');
            }

            // 更新商品状态
            foreach ($params_arr['c_content'] as &$val) {
                $where["c_father_goods_id"] = $val['c_father_goods_id'];
                $up["state"] = $val['state'];
                if ($this->wpsGoodsModel->updateData($where, $up) === false) {
                    throw new Exception("更新失败");
                }
            }
            Db::commit();
            return [1, "更新成功"];
        } catch (Exception $e) {
            Db::rollback();
            return [0, $e->getMessage()];
        }
    }


    /**
     *  商品订单
     */
    public function insOrder($orderInfo)
    {
        // header
        $header = [
//            'channelType:' . 'DONGHUOMUSZ',
            'channelType:' . 'DONGHUOMU',
            'md5:' . $this->getSign($orderInfo)
        ];

        // 额外参数
        $option = [
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_POSTFIELDS => http_build_query($orderInfo),
            CURLOPT_POST => 1
        ];
        Log::log("ins_order_before:" . json_encode($orderInfo, 256));
//        $res = Http::post("https://uat.api.weipinshang.net/mcang/Mcang/createOrder", $orderInfo, $option);
        $res = Http::post("https://api.weipinshang.net/mcang/Mcang/createOrder", $orderInfo, $option);
        Log::log("ins_order:" . $res);
        return $res;
    }

    /**
     *  多商品预下单
     */
    public function insBatchOrder($orderInfo)
    {
        // header
        $header = [
//            'channelType:' . 'DONGHUOMUSZ',
            'channelType:' . 'DONGHUOMU',
            'md5:' . $this->getSign($orderInfo)
        ];

        // 额外参数
        $option = [
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_POSTFIELDS => http_build_query($orderInfo),
            CURLOPT_POST => 1
        ];
        Log::log("ins_batch_order_before:" . json_encode($orderInfo, 256));
//        $res = Http::post("https://uat.api.weipinshang.net/mcang/Mcang/createOrder", $orderInfo, $option);
        $res = Http::post("https://api.weipinshang.net/mcang/Order/preOrder", $orderInfo, $option);
        Log::log("ins_batch_order:" . $res);
        return $res;
    }

    public function pay($orderNo, $payType)
    {
        $params = [
            'orderNo' => $orderNo,
            'payType' => $payType
        ];

        // header
        $header = [
//            'channelType:' . 'DONGHUOMUSZ',
            'channelType:' . 'DONGHUOMU',
            'md5:' . $this->getSign($params)
        ];

        // 额外参数
        $option = [
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_POST => 1
        ];
        Log::log("pay_order_before:");
//        $res = Http::post("https://uat.api.weipinshang.net/mcang/Mcang/payCallBack", $params, $option);
        $res = Http::post("https://api.weipinshang.net/mcang/Mcang/payCallBack", $params, $option);
        $res = json_decode($res, true);
        Log::log("pay_order_res:" . json_encode($res, 256));
        if ($res && isset($res['code']) && $res['code'] == 0) {
            return true;
        } else {
            return $res['msg'] ?? '';
        }
    }

    /**
     * 多商品下单提交订单
     * @param $orderNo
     * @param $cancelBy
     * @return void
     */
    public function pay2($orderNo, $payType)
    {
        $params = [
            'orderNo' => $orderNo,
            'lockCode' => $orderNo
        ];
        Log::log($params);

        // header
        $header = [
//            'channelType:' . 'DONGHUOMUSZ',
            'channelType:' . 'DONGHUOMU',
            'md5:' . $this->getSign($params)
        ];

        // 额外参数
        $option = [
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_POST => 1
        ];
        Log::log("pay2 pay_order_before:");
//        $res = Http::post("https://uat.api.weipinshang.net/mcang/Mcang/payCallBack", $params, $option);
        $res = Http::post("https://api.weipinshang.net/mcang/Order/createOrder", $params, $option);
        $res = json_decode($res, true);
        Log::log("pay2 pay_order_res:" . json_encode($res, 256));
        if ($res && isset($res['code']) && $res['code'] == 0) {
            return true;
        } else {
            return $res['msg'] ?? '';
        }
    }

    public function cancel($orderNo, $cancelBy)
    {
        $params = [
            'orderNo' => $orderNo,
            'cancelBy' => $cancelBy
        ];

        // header
        $header = [
//            'channelType:' . 'DONGHUOMUSZ',
            'channelType:' . 'DONGHUOMU',
            'md5:' . $this->getSign($params)
        ];

        // 额外参数
        $option = [
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_POST => 1
        ];
        Log::log("cancel_order_before:");
//        $res = Http::post("https://uat.api.weipinshang.net/mcang/Mcang/cancelOrder", $params, $option);
        $res = Http::post("https://api.weipinshang.net/mcang/Mcang/cancelOrder", $params, $option);
        Log::log("cancel_order_res:" . json_encode($res, 256));
    }
}
